import { openSpin, openSpinDemo } from "@/api/box";
import { onBuriedPoint } from "@/api/user";
import { useAuth } from "@/store/auth";
import { useBasic } from "@/store/basic";

import type { HitProductListInstance } from "./HitBoxProductList/hitProductList";

export enum OpenBoxType {
  PROD = "spin",
  DEMO = "demo-spin",
}

export const useOpenBox = (
  hitRef: Ref<HitProductListInstance>,
  boxInfo: Ref<API.BOX.BoxListItem>
) => {
  const route = useRoute();
  const basic = useBasic();
  const openBoxLoading = ref(false);

  async function onOpenSpin(type: OpenBoxType) {
    const request = type === OpenBoxType.PROD ? openSpin : openSpinDemo;
    openBoxLoading.value = true;
    const result = await request({
      ids: [Number(route.params.box_id)],
    });
    type === OpenBoxType.PROD && useAuth().getUserAssets();
    if (result !== null) {
      const spinResult = result.spin_result || [];
      if (spinResult.length > 0) {
        const spin = spinResult[0];
        const products = spin?.hit_scroll_product_list || [];
        const index = spin?.hit_scroll_product_list_index || 0;
        hitRef.value?.startSpin(products, index, () => {
          openBoxLoading.value = false;
          if (
            Number(boxInfo.value?.spin_amount || 0) >=
            Number(products[index].amount)
          ) {
            basic.audio.losePlay();
          } else {
            basic.audio.winPlay();
          }
          type === OpenBoxType.PROD && useAuth().getUnprocessedList();
        });
      }

      onBuriedPoint({
        page_name: "boxes-详情",
        action: "点击按钮",
        button_name: type,
        box_id: route.params.box_id as string,
      });
    } else {
      openBoxLoading.value = false;
    }
  }

  function onTick(idx: number) {
    basic.audio.ticksPlay(idx);
  }

  return {
    openBoxLoading,
    onOpenSpin,
    onTick,
  };
};
